<?php
namespace app\api\controller\food;

use app\api\controller\food\Controller;
use app\api\model\food\Order as OrderModel;
use app\api\model\food\Cart as CartModel;
use app\api\model\food\Goods as GoodsModel;
use app\api\model\food\Table as TableModel;
use app\api\model\food\Device;
use hema\Helper;

/**
 * 订单控制器
 */
class Order extends Controller
{
    private $user;

    /**
     * 构造方法
     */
    public function initialize()
    {
        parent::initialize();
        $this->user = $this->getUserDetail();   // 用户信息
    }

    /**
     * 订单确认-购物车结算
	 * $order_mode 点餐模式 10=扫码，20=外卖，30=自取，40=打包
	 * $pay_mode 支付模式 0微信，1余额，2后付款
	 * 店内就餐参数 $people=就餐人数,$ware_price=餐具调料费,$order_pay_price=0
	 * $coupon_user_id 优惠券ID
	 * $message=买家留言
	 * $arrive_time = 到店时间
     */
    public function cart($order_mode,$pay_mode=0,$people=0,$table_id='',$message='',$arrive_time='0,0',$coupon_user_id=0)
    {
        // 商品结算信息
        $model = new OrderModel;
        $order = $model->getCart($this->user,$order_mode,$this->shop_id,$coupon_user_id,$table_id);
        
        //扫码
        if($order_mode==10 and !empty($table_id)){
            $table = TableModel::get($table_id);
			//如果餐桌状态空闲中才进行验证，否则为加单
			if($table['status']['value'] == 10){
			    $order['is_order'] = 1;//点单
		        $order['table_name'] = $table['table_name'] . '（点单）';
				//餐桌容纳人数
				if($table['people'] < $people){
					return $this->renderError('该（包间/餐桌）只能容纳'.$table['people'].'人');
				}
				//最低消费
				if($table['consume'] > $order['order_pay_price']){
					return $this->renderError('该（包间/餐桌）未达到最低消费￥'.$table['consume'].'元');
				}
				//计算所需餐具调料费
				if($table['ware_price']>0){
					$order['ware_price'] = Helper::number2($table['ware_price'] * $people);
					$order['order_pay_price'] = Helper::number2($order['order_pay_price']+$order['ware_price']);
				}
			}else{
			    $order['is_order'] = 0;//加单
		        $order['table_name'] = $table['table_name'] . '（加单）';
			}
        }
        if (!$this->request->isPost()) {
            return $this->renderSuccess($order);
        }
        //扫码
        if($order_mode==10){
    		$order['table_id'] = $table_id;
			$order['people'] = $people;
        }else{
        	//排号
        	$order['row_no'] = row_no($this->applet_id,$this->shop_id);
        }
        //取餐时间计算
        $arrive = explode(',',$arrive_time);
        if($arrive[0] == 0 and $arrive[1] == 0){
            $order['arrive_time'] = time();
        }else{
            $timestamp = strtotime(date('Y-m-d'.'00:00:00',time()));//今天的起始时间戳
            //今天
            if($arrive[0] == 0){
                $order['arrive_time'] = $timestamp + (int)$arrive[1];
            }
            //明天
            if($arrive[0] == 1){
                $order['arrive_time'] = $timestamp + (int)$arrive[1] + 86400;
            }
            //后天
            if($arrive[0] == 2){
                $order['arrive_time'] = $timestamp + (int)$arrive[1] + (86400 * 2);
            }
            
        }
		$order['message'] = $message;
		$order['order_mode'] = $order_mode;
		$order['user_id'] = $this->user['user_id'];
		$order['shop_id'] = $this->shop_id;
		$order['applet_id'] = $this->applet_id;
        // 创建订单
        if (!$model->add($order,$coupon_user_id)) {
			$error = $model->getError() ?: '订单创建失败';
			return $this->renderError($error);  
        }
		// 清空购物车
		$Card = new CartModel($this->user['user_id'],$this->shop_id,$this->applet_id,$table_id);
		$Card->clearAll();
		$order = OrderModel::detail($model['order_id']);
		if($data = $order->userPay($pay_mode)){
            return $this->renderSuccess($data);
        }
        $error = $order->getError() ?: '支付失败';
        return $this->renderError($error);
    }

    /**
     * 呼叫服务员
     */
    public function spk($order_id,$mode)
    {
        $model = OrderModel::detail($order_id);
        Device::push($this->shop_id,$mode,$model['table']['row_no']);
        return $this->renderMsg('操作成功');
    }
}
